package com.mlink.job;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.base.commons.utils.BeanUtils;
import com.base.commons.utils.HttpClientUtils;
import com.base.commons.web.utils.PropertyUtil;
import com.mlink.job.quartz.annoations.Job;
import com.mlink.job.quartz.annoations.JobMethod;
import com.mlink.job.quartz.entity.Holiday;
import com.mlink.job.quartz.service.HolidayService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 每年1月1日4点获取法定节假日
 * Created by Irany  2017/12/18 9:36
 */
@Component
@Job(name = "每年1月1日4点获取法定节假日", cronExpression = "0 0 4 1 1 *")//0 0 4 1 1 *   //0/5 * * ? * MON-FRI
public class GetHolidayJob {


    @JobMethod
    public void doJob() {
        try {
            getHoliday();
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("每年1月1日获取当前年份节假日失败,msg:{}", e.getMessage());
        }
    }

    private void getHoliday() throws Exception {
        Calendar calendar=Calendar.getInstance();
        String year=String.valueOf(calendar.get(Calendar.YEAR));
        String json = HttpClientUtils.get(PropertyUtil.get("holiday.url") + year);
        Map<String, Object> map = BeanUtils.toBean(json, HashMap.class);
        Map<String, String> holidays = (Map<String, String>) map.get(year);
        service.delete(new EntityWrapper<Holiday>().where("id!={0}",-1));
        for (Map.Entry<String, String> entry :
                holidays.entrySet()) {
            Holiday entity = new Holiday();
            entity.setValue(entry.getKey());
            entity.setIsHoliday(Integer.valueOf(entry.getValue()));
            service.insert(entity);
        }
        logger.debug("每年1月1日获取当前年份节假日");

    }


    @Autowired
    private HolidayService service;

    private Logger logger = LoggerFactory.getLogger(getClass());
}
